package sdk.webview.fmc.com.fmcsdk.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import sdk.webview.fmc.com.fmcsdk.check.bean.ActivityJsonBean;
import sdk.webview.fmc.com.fmcsdk.util.KLog;

public class DatabaseManager {
    private static DBHelper dbHelper;
    private static SQLiteDatabase database;
//    ExecutorService executor = Executors.newSingleThreadExecutor();
//    private static class DatabaseManagerHolder{
//        private static final DatabaseManager INSTANCE = new DatabaseManager();
//    }
//
//    private DatabaseManager() {}
//
//    public static DatabaseManager getInstance(Context context) {
//        dbHelper = new DBHelper(context);
//        database = dbHelper.getWritableDatabase();
//        return DatabaseManagerHolder.INSTANCE;
//    }


    public DatabaseManager(Context context) {
        dbHelper = new DBHelper(context);
        database = dbHelper.getWritableDatabase();
    }

    // 插入数据
    public synchronized long insertJson(String name, String json) {
        ContentValues values = new ContentValues();
        values.put(ActivityJson.ACTIVITY_NAME, name);
        values.put(ActivityJson.ACTIVITY_JSON, json);
        return database.insert(ActivityJson.TABLE_NAME, null, values);
    }


    // 更新数据
    public synchronized int updateUser(String name, String json) {
        ContentValues values = new ContentValues();
        values.put(ActivityJson.ACTIVITY_NAME, name);
        values.put(ActivityJson.ACTIVITY_JSON, json);
        return database.update(ActivityJson.TABLE_NAME, values, ActivityJson.ACTIVITY_NAME + "=?", new String[]{String.valueOf(name)});
    }

    // 根据查询用户
    public synchronized ActivityJsonBean getUserByName(String name) {
        Cursor cursor = database.query(
                ActivityJson.TABLE_NAME,
                new String[]{ActivityJson.ACTIVITY_NAME, ActivityJson.ACTIVITY_JSON},
                ActivityJson.ACTIVITY_NAME + "=?",
                new String[]{name},
                null, null, null);

        if (cursor != null && cursor.moveToFirst()) {
            String nameNew = cursor.getString(cursor.getColumnIndex(ActivityJson.ACTIVITY_NAME));
            String jsonNew = cursor.getString(cursor.getColumnIndex(ActivityJson.ACTIVITY_JSON));
            cursor.close();
            return new ActivityJsonBean(nameNew, jsonNew);
        }

        if (cursor != null) {
            cursor.close();
        }

        return null;
    }




    // 插入或更新用户
    public synchronized long upsertJson(String name, String json) {
        KLog.e(name);
        KLog.e(json);
        ActivityJsonBean existingUser = getUserByName(name);
        if (existingUser != null) {
            // 用户已存在，更新数据
            int updateResult = updateUser(name, json);
            return updateResult > 0 ? 1 : -1;
        } else {
            // 用户不存在，插入数据
            return insertJson(name, json);
        }
    }



    // 查询所有未上传的巡检点数据
    public synchronized List<InspectPoint> getInspectPointList() {


        List<InspectPoint> inspectPointList = new ArrayList<>();

        // 定义查询的条件
        String selection = "isUpload = ?";
        String[] selectionArgs = {"N"};

        // 执行查询
        Cursor cursor = database.query(
                "inspect_point",    // 表名
                new String[]{"_id", "data", "isUpload"}, // 要查询的列
                selection,        // WHERE 子句
                selectionArgs,    // WHERE 子句的参数
                null,             // GROUP BY
                null,             // HAVING
                null              // ORDER BY
        );

        // 遍历查询结果
        if (cursor != null) {
            while (cursor.moveToNext()) {
                long id = cursor.getLong(cursor.getColumnIndex("_id"));
                String data = cursor.getString(cursor.getColumnIndex("data"));
                String isUpload = cursor.getString(cursor.getColumnIndex("isUpload"));
                String point = cursor.getString(cursor.getColumnIndex("point"));

                InspectPoint inspectPic = new InspectPoint(id,data,isUpload,point);
                inspectPointList.add(inspectPic);
            }
            cursor.close();  // 关闭 Cursor
        }


        // 返回查询结果
        return inspectPointList;
    }



    // 新增未上传的巡检点数据
    public synchronized long insertInspectPoint(String json) {
        ContentValues values = new ContentValues();
        values.put(InspectPoint.IS_UPLOAD, "N");
        values.put(InspectPoint.DATA, json);
        return database.insert(InspectPoint.TABLE_NAME, null, values);
    }

    //更新未上传的巡检点 为 已上传
    public synchronized boolean updateInspectPoint(long id) {
        // 创建ContentValues对象用于更新
        ContentValues values = new ContentValues();
        values.put("isUpload", "Y");  // 设置isUpload字段的值为"Y"

        // 使用更新操作，修改指定ID的数据
        String whereClause = "_id = ?";  // 设置查询条件，查找指定的id
        String[] whereArgs = new String[]{String.valueOf(id)};  // id是要查询的指定id，转换为字符串

        // 执行更新操作
        int rowsAffected = database.update(InspectPoint.TABLE_NAME, values, whereClause, whereArgs);
        database.close();
        return rowsAffected > 0;
    }


    // 查询所有未上传的巡检点图片数据
    public synchronized List<InspectPic> getInspectPointPic() {
        List<InspectPic> inspectPicList = new ArrayList<>();
        // 定义查询的条件
        String selection = "isUpload = ?";
        String[] selectionArgs = {"N"};

        // 执行查询
        Cursor cursor = database.query(
                "inspect_pic",    // 表名
                new String[]{"_id", "data", "isUpload","point","des"}, // 要查询的列
                selection,        // WHERE 子句
                selectionArgs,    // WHERE 子句的参数
                null,             // GROUP BY
                null,             // HAVING
                null              // ORDER BY
        );

        // 遍历查询结果
        if (cursor != null) {
            while (cursor.moveToNext()) {
                long id = cursor.getLong(cursor.getColumnIndex("_id"));
                String data = cursor.getString(cursor.getColumnIndex("data"));
                String isUpload = cursor.getString(cursor.getColumnIndex("isUpload"));
                String point = cursor.getString(cursor.getColumnIndex("point"));
                String des = cursor.getString(cursor.getColumnIndex("des"));
                InspectPic inspectPic = new InspectPic(id,data,isUpload,point,des);
                inspectPicList.add(inspectPic);
            }
            cursor.close();  // 关闭 Cursor
        }

        // 关闭 Cursor
        if (cursor != null) {
            cursor.close();
        }

        // 返回查询结果
        return inspectPicList;
    }

    // 新增未上传的巡检图片数据
    public synchronized long insertInspectPic(String json) {
        ContentValues values = new ContentValues();
        values.put(InspectPic.IS_UPLOAD, "N");
        values.put(InspectPic.DATA, json);
        return database.insert(InspectPic.TABLE_NAME, null, values);
    }



    //更新未上传的巡检图片 为 已上传
    public synchronized boolean updateInspectPic(long id) {
        // 创建ContentValues对象用于更新
        ContentValues values = new ContentValues();
        values.put("isUpload", "Y");  // 设置isUpload字段的值为"Y"

        // 使用更新操作，修改指定ID的数据
        String whereClause = "_id = ?";  // 设置查询条件，查找指定的id
        String[] whereArgs = new String[]{String.valueOf(id)};  // id是要查询的指定id，转换为字符串

        // 执行更新操作
        int rowsAffected = database.update(InspectPic.TABLE_NAME, values, whereClause, whereArgs);
        database.close();
        return rowsAffected > 0;
    }

    //更新未上传的巡检图片 为 已上传
    public synchronized boolean deleteInspectPic(String id) {
        // 创建ContentValues对象用于更新
        // 使用更新操作，修改指定ID的数据
        String whereClause = "_id = ?";  // 设置查询条件，查找指定的id
        String[] whereArgs = new String[]{String.valueOf(id)};  // id是要查询的指定id，转换为字符串
        // 执行更新操作
        int rowsAffected = database.delete(InspectPic.TABLE_NAME, whereClause, whereArgs);
        database.close();
        return rowsAffected > 0;
    }



    // 查询所有未上传的巡检单状态
    public synchronized List<InspectState> getInspectState() {
        List<InspectState> inspectStateList = new ArrayList<>();

        // 定义查询的条件
        String selection = "isUpload = ?";
        String[] selectionArgs = {"N"};

        // 执行查询
        Cursor cursor = database.query(
                "inspect_state",    // 表名
                new String[]{"_id", "data", "isUpload","point"}, // 要查询的列
                selection,        // WHERE 子句
                selectionArgs,    // WHERE 子句的参数
                null,             // GROUP BY
                null,             // HAVING
                null              // ORDER BY
        );

        // 遍历查询结果
        if (cursor != null) {
            while (cursor.moveToNext()) {
                long id = cursor.getLong(cursor.getColumnIndex("_id"));
                String data = cursor.getString(cursor.getColumnIndex("data"));
                String isUpload = cursor.getString(cursor.getColumnIndex("isUpload"));
                String point = cursor.getString(cursor.getColumnIndex("point"));
                // 创建 InspectPic 对象并加入列表
                InspectState inspectPic = new InspectState(id,data,isUpload,point);
                inspectStateList.add(inspectPic);
            }
            cursor.close();  // 关闭 Cursor
        }


        // 返回查询结果
        return inspectStateList;
    }

    // 新增未上传的巡检单状态
    public synchronized long insertInspectState(String json) {
        ContentValues values = new ContentValues();
        values.put(InspectState.IS_UPLOAD, "N");
        values.put(InspectState.DATA, json);
        return database.insert(InspectState.TABLE_NAME, null, values);
    }



    //更新未上传的巡检单 为 已上传
    public synchronized boolean updateInspectState(long id) {
        // 创建ContentValues对象用于更新
        ContentValues values = new ContentValues();
        values.put("isUpload", "Y");  // 设置isUpload字段的值为"Y"

        // 使用更新操作，修改指定ID的数据
        String whereClause = "_id = ?";  // 设置查询条件，查找指定的id
        String[] whereArgs = new String[]{String.valueOf(id)};  // id是要查询的指定id，转换为字符串

        // 执行更新操作
        int rowsAffected = database.update(InspectState.TABLE_NAME, values, whereClause, whereArgs);
        database.close();
        return rowsAffected > 0;
    }



    // 关闭数据库
    public void close() {
        if (database != null) {
            database.close();
        }

    }
    /**
     * 删除数据库中所有相关表的数据。
     *
     * @return 如果所有删除操作都成功返回true，否则返回false
     */
    public synchronized boolean deleteAllData() {
        database.beginTransaction();
        try {
            // 删除各表的数据
            database.delete(InspectPic.TABLE_NAME, null, null);
            database.delete(InspectPoint.TABLE_NAME, null, null);
            database.delete(InspectState.TABLE_NAME, null, null);
            database.delete(ActivityJson.TABLE_NAME, null, null);

            database.setTransactionSuccessful(); // 标记事务完成
            return true;
        } catch (Exception e) {
            e.printStackTrace(); // 或者使用日志记录工具记录错误信息
            return false;
        } finally {
            database.endTransaction(); // 结束事务
        }
    }
}
